﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;

namespace LicPdaService
{
    public class Check
    {
        /// <summary>
        /// 1.0原料到货验收
        /// DataSource:Orders
        /// </summary>
        public static string status_check = "true";

        public static string GetCheck(string xml)
        {
            string strSql = string.Empty;

            App.Connection();
            App.DBconSet();

            //1接收验货的XML
            DataTable ldt = App.Xml2DataTable(xml);
            if (ldt.Rows.Count == 0)
            {
                return "";
            }
            //string lstrans = App.ws.CreateTrans();
            DataTable ldt_ys = null;
            try
            {
                App.swhseid = ldt.Rows[0]["whseid"].ToString();
                App.suserid = ldt.Rows[0]["userid"].ToString();
                App.sasn = ldt.Rows[0]["asn"].ToString();
                strSql = "select recstatus.status,receipt.shipkey,receipt.type,receipt.data_from  from receipt left join recstatus on receipt.status=recstatus.status where  receipt.whseid='" + App.swhseid + "' and receiptkey='" + App.sasn + "' ";
                DataTable ldt_asn = App.GetDataTable(App.DBconWMS, strSql, "receipt");
                //DataTable ldt_asn = App.ws.GetTable("select recstatus.status,receipt.shipkey  from receipt left join recstatus on receipt.status=recstatus.status where recstatus.status in('01','03')  and receipt.whseid='" + App.swhseid + "' and receiptkey='" + App.sasn + "' ", "", false, "");
                strSql = "select * from  ReceiptDetail where whseid='" + App.swhseid + "' and receiptkey='" + App.sasn + "' and (lpn IS NULL or lpn = '')";
                DataTable ldt_asn_detail = App.GetDataTable(App.DBconWMS, strSql, "ReceiptDetail");
                //DataTable ldt_asn_detail = App.ws.GetTable("select * from  ReceiptDetail where whseid='" + App.swhseid + "' and receiptkey='" + App.sasn + "'","detail",true,"");

                //ldt_ys = GetCheck_Logic(ldt, ldt_asn, ldt_asn_detail, lstrans);
                ldt_ys = GetCheck_Logic(ldt, ldt_asn, ldt_asn_detail, "");
                //App.ws.CommitTrans(lstrans);
            }
            catch (Exception ex)
            {
                App.Log("Check", ex.Message.ToString());
                //App.ws.RollbackTrans(lstrans);
                throw;
            }


            return GetCheck_Return(ldt_ys);
        }


        //到货验收逻辑
        public static DataTable GetCheck_Logic(DataTable ldt, DataTable ldt_asn, DataTable ldt_asn_detail, string lstrans)
        {
            string lscustomer_code = "";
            status_check = "true";
            List<string> sqllists = new List<string>();
            List<string> skulist = new List<string>();
            string strSql = string.Empty;
            string sku = string.Empty;
            string asn = string.Empty;
            int qty = 0;
            int qty_yb = 0;
            int qty_sm = 0;
            int qty_ybsm = 0;

            DataTable ldt_ys = LicPdaService.App.GetCreateDataTable();
            try
            {
                #region  构建验收DataTable
                for (int i = 0; i < ldt.Rows.Count; i++)
                {

                    string[] ls;
                    ls = ldt.Rows[i]["master_label"].ToString().Split('|');
                    if (ls.Length == 5 || ls.Length == 4)
                    {
                        DataRow[] ldrs = null;
                        if (ls.Length == 5)
                        {
                            string lswhere = "asn='" + App.sasn + "' and sku='" + ls[0].ToString() + "' and lottable02='" + ls[1].ToString() + "' and lottable01='" + ls[2].ToString() + "' and shipkey='" + ls[4].ToString() + "'";
                            if (ldt_asn.Rows[0]["data_from"].ToString() == "CMS")
                            {
                                lswhere = "asn='" + App.sasn + "' and sku='" + ls[0].ToString() + "' and lottable02='" + ls[1].ToString() + "'  and shipkey='" + ls[4].ToString() + "'";
                            }
                            ldrs = ldt_ys.Select(lswhere);
                        }
                        else if (ls.Length == 4)
                        {
                            string lswhere = "asn='" + App.sasn + "' and sku='" + ls[0].ToString() + "' and lottable02='" + ls[1].ToString() + "' and lottable01='" + ls[2].ToString() + "' ";
                            if (ldt_asn.Rows[0]["data_from"].ToString() == "CMS")
                            {
                                lswhere = "asn='" + App.sasn + "' and sku='" + ls[0].ToString() + "' and lottable02='" + ls[1].ToString() + "'  ";
                            }
                            ldrs = ldt_ys.Select(lswhere);
                        }
                        if (ldrs.Length == 0)
                        {
                            DataRow ldr = ldt_ys.NewRow();
                            ldr["asn"] = App.sasn;
                            ldr["sku"] = ls[0].ToString();
                            ldr["lottable02"] = ls[1].ToString();
                            ldr["lottable01"] = ls[2].ToString();
                            if (ls.Length == 5)
                            {
                                ldr["shipkey"] = ls[4].ToString();
                            }
                            else
                            {
                                ldr["shipkey"] = ldt_asn.Rows[0]["shipkey"].ToString();
                            }
                            ldr["qty"] = Convert.ToSingle(ls[3].ToString());
                            ldr["master_label"] = ldt.Rows[i]["master_label"].ToString();
                            ldr["userid"] = App.suserid;
                            ldr["whseid"] = App.swhseid;
                            ldt_ys.Rows.Add(ldr);
                        }
                        else
                        {
                            ldrs[0]["qty"] = Convert.ToSingle(ldrs[0]["qty"].ToString()) + Convert.ToSingle(ls[3].ToString());
                        }
                    }
                }
                //3根据ASN单号获取ASN预报信息--默认验收时为同一ASN单号
                if (ldt_ys.Rows.Count > 0)
                {

                    if (ldt.Rows.Count == 0)
                    {
                        for (int i = 0; i < ldt_ys.Rows.Count; i++)
                        {
                            ldt_ys.Rows[i]["msg"] = "没有找到要验收的ASN";
                        }
                        return ldt_ys;
                    }
                }
                #endregion

                #region 新增预报信息 ASN+料号+订单号 的卡控逻辑 quinn
                for (int i = 0; i < ldt_ys.Rows.Count; i++)
                {
                    DataRow[] ldrs = ldt_asn_detail.Select("receiptkey='" + ldt_ys.Rows[i]["asn"].ToString() + "' and sku='" + ldt_ys.Rows[i]["sku"].ToString() + "' and lottable02='" + ldt_ys.Rows[i]["lottable02"].ToString() + "' ");
                    if (ldrs.Length == 0)
                    {
                        status_check = "ASN预报中不存在 料号:" + ldt_ys.Rows[i]["sku"].ToString() + "+订单号:" + ldt_ys.Rows[i]["lottable02"].ToString() + "的预报组合信息，无法执行验收&上架！";
                    }
                }
                #endregion

                #region 新增预报信息量与实物扫描数量匹配逻辑 quinn
                if(status_check == "true") //优化 只有判定条件全部通过才继续执行
                {
                    //料号数量汇总
                    DataTable ldt_sk = LicPdaService.App.GetCreateDataTable();
                    for (int i = 0; i < ldt_ys.Rows.Count; i++)
                    {
                        string[] ls;
                        ls = ldt_ys.Rows[i]["master_label"].ToString().Split('|');
                        DataRow[] ldrs = null;
                        string lswhere = "asn='" + App.sasn + "' and sku='" + ls[0].ToString() + "'";
                        ldrs = ldt_sk.Select(lswhere);
                        if (ldrs.Length == 0)
                        {
                            DataRow ldr = ldt_sk.NewRow();
                            ldr["asn"] = App.sasn;
                            ldr["sku"] = ls[0].ToString();
                            ldr["qty"] = Convert.ToSingle(ldt_ys.Rows[i]["qty"].ToString());
                            ldr["userid"] = App.suserid;
                            ldr["whseid"] = App.swhseid;
                            ldt_sk.Rows.Add(ldr);
                        }
                        else
                        {
                            ldrs[0]["qty"] = Convert.ToSingle(ldrs[0]["qty"].ToString()) + Convert.ToSingle(ldt_ys.Rows[i]["qty"].ToString());
                        }

                    }

                    //扫描验收数量卡控
                    for (int i = 0; i < ldt_sk.Rows.Count; i++)
                    {
                        asn = ldt_sk.Rows[i]["asn"].ToString();
                        sku = ldt_sk.Rows[i]["sku"].ToString();
                        qty = Int32.Parse(ldt_sk.Rows[i]["qty"].ToString());


                        strSql = "SELECT sku,SUM(pre_qty) AS qty_yb,SUM(check_qty) AS qty_ybsm   FROM [LicWMS].[dbo].[ReceiptDetail]";
                        strSql += " WHERE   receiptkey='" + asn + "' and whseid='" + App.swhseid + "' and sku='" + sku + "' and pre_qty>0 GROUP BY sku";
                        DataTable ldt_yb = App.GetDataTable(App.DBconWMS, strSql, "ReceiptDetail");

                        if (ldt_yb.Rows.Count > 0)
                        {
                            //预报数量
                            qty_yb = Int32.Parse(ldt_yb.Rows[0]["qty_yb"].ToString().Substring(0, ldt_yb.Rows[0]["qty_yb"].ToString().Length - 3));
                            //料号+批次+订单号 一致 汇总已扫描数量
                            qty_ybsm = Int32.Parse(ldt_yb.Rows[0]["qty_ybsm"].ToString().Substring(0, ldt_yb.Rows[0]["qty_ybsm"].ToString().Length - 3));

                            strSql = "SELECT sku,SUM(check_qty) AS qty_sm   FROM [LicWMS].[dbo].[ReceiptDetail]";
                            strSql += " WHERE   receiptkey='" + asn + "' and whseid='" + App.swhseid + "' and sku='" + sku + "' AND (loc IS NULL OR loc='') AND pre_qty=0  GROUP BY sku";
                            DataTable ldt_sm = App.GetDataTable(App.DBconWMS, strSql, "ReceiptDetail");
                            if (ldt_sm.Rows.Count > 0)
                            {
                                //料号+批次+订单号 不一致 汇总已扫描数量
                                qty_sm = Int32.Parse(ldt_sm.Rows[0]["qty_sm"].ToString().Substring(0, ldt_sm.Rows[0]["qty_sm"].ToString().Length - 3));
                            }
                            if (qty + qty_ybsm + qty_sm > qty_yb)
                            {
                                status_check = "料号：" + sku + " 的 预报数量:" + qty_yb.ToString() + " 小于 累计验收扫描数量总和:" + (qty + qty_ybsm + qty_sm).ToString() + "，无法执行PDA验收&上架！ - 提示来自 验收数量卡控";
                            }
                        }
                        else
                        {
                            status_check = "料号：" + sku + " 没有维护预报信息，无法进行PDA验收&上架 - 提示来自 料号验收卡控";
                        }
                    }
                }
                #endregion

                #region 执行验收
                if(status_check == "true") //优化 只有判定条件全部通过才继续执行
                {
                    if (ldt_asn_detail.Rows.Count > 0)
                    {
                        lscustomer_code = ldt_asn_detail.Rows[0]["customer_code"].ToString();
                    }
                    Int32 lsline_no = ldt_asn_detail.Rows.Count;
                    strSql = "SELECT MAX(line_no) AS line_no FROM [LicWMS].[dbo].[ReceiptDetail] WHERE   receiptkey='" + App.sasn + "' and whseid='" + App.swhseid + "'";
                    DataTable dtln = App.GetDataTable(App.DBconWMS, strSql, "ReceiptDetail");
                    if (dtln.Rows.Count > 0)
                    {
                        //Int32 lsline_no = ldt_asn_detail.Rows.Count;
                        lsline_no = Int32.Parse(dtln.Rows[0]["line_no"].ToString());
                    }


                    for (int i = 0; i < ldt_ys.Rows.Count; i++)
                    {
                        DataRow[] ldrs = ldt_asn_detail.Select("receiptkey='" + ldt_ys.Rows[i]["asn"].ToString() + "' and sku='" + ldt_ys.Rows[i]["sku"].ToString() + "' and lottable02='" + ldt_ys.Rows[i]["lottable02"].ToString() + "' and lottable01='" + ldt_ys.Rows[i]["lottable01"].ToString() + "' ");
                        if (ldt_asn.Rows[0]["data_from"].ToString() == "CMS")
                        {
                            ldrs = ldt_asn_detail.Select("receiptkey='" + ldt_ys.Rows[i]["asn"].ToString() + "' and sku='" + ldt_ys.Rows[i]["sku"].ToString() + "' and lottable02='" + ldt_ys.Rows[i]["lottable02"].ToString() + "' ");
                        }
                        if (ldrs.Length == 0)
                        {
                            //无预报信息，补加
                            string qc_man = "";
                            string qc_status = "";
                            DataRow[] ldrs_qc = ldt_asn_detail.Select("receiptkey='" + ldt_ys.Rows[i]["asn"].ToString() + "' and sku='" + ldt_ys.Rows[i]["sku"].ToString() + "' ");
                            if (ldrs_qc.Length > 0)
                            {
                                qc_man = ldrs_qc[0]["qc_man"].ToString();
                                qc_status = ldrs_qc[0]["qc_status"].ToString();
                            }

                            ldt_ys.Rows[i]["pre_qty"] = 0;
                            lsline_no += 1;
                            strSql = "select description,packey,unit,lottable10 from sku where sku='" + ldt_ys.Rows[i]["sku"].ToString() + "'";
                            DataTable ldt_sku = App.GetDataTable(App.DBconWMS, strSql, "sku");
                            string lsskudescr = "";
                            string lslottable09 = "";
                            string lsuom = "";
                            string lslottable10 = "";
                            if (ldt_sku.Rows.Count > 0)
                            {
                                try
                                {
                                    lsskudescr = ldt_sku.Rows[0]["description"].ToString();
                                    lslottable09 = ldt_sku.Rows[0]["packey"].ToString();
                                    lsuom = ldt_sku.Rows[0]["unit"].ToString();
                                    lslottable10 = ldt_asn.Rows[0]["shipkey"].ToString(); //抓取WebPortal导入供应商代码
                                }
                                catch { }

                                string lottable03 = App.sasn.ToString() + lsline_no.ToString().PadLeft(5, '0').ToString();
                                string lssql = "insert into ReceiptDetail(whseid,receiptkey,line_no,customer_code,sku,skudescr,lottable09,lottable10,uom,status,pre_qty,unrec_qty,goodqty,qc_man,qc_status,lottable01,lottable02,lottable03,lottable04,lottable05,addwho,adddate,check_qty) values(";
                                lssql += "'" + App.swhseid + "','" + App.sasn + "','" + lsline_no.ToString().PadLeft(5, '0') + "','" + lscustomer_code + "','" + ldt_ys.Rows[i]["sku"].ToString() + "'";
                                lssql += ",'" + lsskudescr + "','" + lslottable09 + "','" + lslottable10 + "','" + lsuom + "','03',0,0,0,'" + qc_man + "','" + qc_status + "','" + ldt_ys.Rows[i]["lottable01"].ToString() + "','" + ldt_ys.Rows[i]["lottable02"].ToString() + "','" + lottable03 + "','" + System.DateTime.Now.ToString() + "','" + System.DateTime.Now.ToString() + "'";
                                lssql += ",'" + App.suserid + "','" + System.DateTime.Now.ToString() + "'," + ldt_ys.Rows[i]["qty"] + ")";
                                sqllists.Add(lssql);
                                //日志
                                string lssql1 = "insert into RecHistoryDtl(whseid,receiptkey,line_no,status,operation,sku,addwho,adddate) values";
                                lssql1 += "('" + App.swhseid + "','" + App.sasn + "','" + lsline_no.ToString().PadLeft(5, '0') + "','03','PDA验收','" + ldt_ys.Rows[i]["sku"].ToString() + "','" + App.suserid + "','" + System.DateTime.Now.ToString() + "')";
                                sqllists.Add(lssql1);
                            }
                            else
                            {
                                status_check = "料号:" + ldt_ys.Rows[i]["sku"].ToString() + " 未维护基础资料，无法验收&上架";
                            }
                            strSql = "SELECT KBPO#,KBPT#,KBISTS FROM [LicWMS].[dbo].[CMS_AD_POI] WHERE KBPO#='" + ldt_ys.Rows[i]["lottable02"].ToString() + "' AND KBPT#='" + ldt_ys.Rows[i]["sku"].ToString() + "'";
                            DataTable ldt_cm = App.GetDataTable(App.DBconWMS, strSql, "CMS_AD_POI");
                            if (ldt_cm.Rows.Count <= 0)
                            {
                                status_check = "料号:" + ldt_ys.Rows[i]["sku"].ToString() + "与订单号:" + ldt_ys.Rows[i]["lottable02"].ToString() + "对应关系错误，无法验收&上架";
                            }

                        }
                        else
                        {
                            ldt_ys.Rows[i]["pre_qty"] = ldrs[0]["pre_qty"];

                            ldt_ys.Rows[i]["qty"] = Convert.ToSingle(ldt_ys.Rows[i]["qty"].ToString()) + Convert.ToSingle(ldrs[0]["check_qty"].ToString());
                            string lssql_detail = "update receiptdetail set status='03',check_qty=" + ldt_ys.Rows[i]["qty"].ToString() + " where whseid='" + App.swhseid + "' and line_no='" + ldrs[0]["line_no"] + "'   and receiptkey='" + App.sasn + "'";
                            if (ldt_asn.Rows[0]["data_from"].ToString() == "CMS")
                            {
                                lssql_detail = "update receiptdetail set lottable01='" + ldt_ys.Rows[i]["lottable01"].ToString() + "', status='03',check_qty=" + ldt_ys.Rows[i]["qty"].ToString() + " where whseid='" + App.swhseid + "' and line_no='" + ldrs[0]["line_no"] + "'   and receiptkey='" + App.sasn + "'";
                            }
                            sqllists.Add(lssql_detail);
                            //明细日志
                            string lssql1 = "insert into RecHistoryDtl(whseid,receiptkey,line_no,status,operation,sku,addwho,adddate) values";
                            lssql1 += "('" + App.swhseid + "','" + App.sasn + "','" + ldrs[0]["line_no"] + "','03','PDA验收','" + ldt_ys.Rows[i]["sku"].ToString() + "','" + App.suserid + "','" + System.DateTime.Now.ToString() + "')";
                            sqllists.Add(lssql1);
                        }
                    }

                    //4、更新主表状态
                    sqllists.Add("update receipt set status='03' where whseid='" + App.swhseid + "' and receiptkey='" + App.sasn + "'");
                    //5、主档日志
                    sqllists.Add("insert into RecHistory(whseid,receiptkey,status,operation,addwho,adddate) values('" + App.swhseid + "','" + App.sasn + "','03','PDA验收','" + App.suserid + "','" + System.DateTime.Now.ToString() + "')");

                    if (status_check == "true") //只有判定条件 全部通过才执行数据写入
                    {
                        App.ExecuteSQLScriptLists(sqllists, App.DBconWMS);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                #region
                App.Log("GetCheck_Logic", ex.Message.ToString());
                for (int i = 0; i < ldt_ys.Rows.Count; i++)
                {
                    ldt_ys.Rows[i]["msg"] = ex.ToString();
                }
                return ldt_ys;
                throw;
                #endregion
            }

            #region 返回状态信息
            for (int i = 0; i < ldt_ys.Rows.Count; i++)
            {
                if (status_check == "true") //成功信息
                {
                    ldt_ys.Rows[i]["msg"] = "送货数量:" + ldt_ys.Rows[i]["pre_qty"].ToString() + "  验收数量:" + ldt_ys.Rows[i]["qty"].ToString();
                }
                else //失败信息
                {
                    ldt_ys.Rows[i]["msg"] = status_check;
                }
            }
            #endregion

            return ldt_ys;
        }

        //到货验收--返回值
        public static string GetCheck_Return(DataTable ldt)
        {
            XmlDocument doc = new XmlDocument();//返回报文
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            XmlElement rootRet = doc.CreateElement("NewDataSet");

            for (int i = 0; i < ldt.Rows.Count; i++)
            {
                XmlNode checkNodes = doc.CreateElement("check_return");//返回用户节点
                XmlElement lxeasn = doc.CreateElement("asn");
                XmlElement lxemaster_label = doc.CreateElement("master_label");
                XmlElement lxereturn_status = doc.CreateElement("return_status");
                XmlElement lxeuserid = doc.CreateElement("userid");
                XmlElement lxewhseid = doc.CreateElement("whseid");


                lxeasn.InnerText = ldt.Rows[i]["asn"].ToString();
                lxemaster_label.InnerText = ldt.Rows[i]["master_label"].ToString();
                string lstr = "料号:" + ldt.Rows[i]["sku"].ToString() + "  订单号:" + ldt.Rows[i]["lottable02"].ToString() + " 批次:" + ldt.Rows[i]["lottable01"].ToString();
                if (ldt.Rows[i]["msg"].ToString() != "")
                {
                    lstr += "  状态:" + ldt.Rows[i]["msg"].ToString();
                }
                else
                {
                    lstr += "  验收数量:" + ldt.Rows[i]["sku"].ToString();
                }

                if (status_check != "true")
                {
                    lstr = "验收&上架失败！！！原因： " + status_check;
                }

                lxereturn_status.InnerText = lstr;
                lxeuserid.InnerText = ldt.Rows[i]["userid"].ToString();
                lxewhseid.InnerText = ldt.Rows[i]["whseid"].ToString();
                checkNodes.AppendChild(lxeasn);
                checkNodes.AppendChild(lxemaster_label);
                checkNodes.AppendChild(lxereturn_status);
                checkNodes.AppendChild(lxeuserid);
                checkNodes.AppendChild(lxewhseid);
                rootRet.AppendChild(checkNodes);
            }


            doc.AppendChild(rootRet);
            return doc.InnerXml;
        }
    }
}
